//
//  TMGGuessViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/15.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGGuessViewController.h"
#import "TMGCommentTableViewCell.h"
#import "TMGCommentViewController.h"
#import "TMGFromViewController.h"
#import "TMWaveView.h"
#import "TMGCommentModel.h"
@interface TMGGuessViewController ()
@property(nonatomic, strong) TMWaveView                     *upWaveControl;
@property(nonatomic, strong) TMWaveView                     *lowWaveControl;
@property(nonatomic, strong) NSMutableArray <TMGCommentModel*>                    *dataSouce;
@property(nonatomic, assign) NSInteger                      page;
@end

@implementation TMGGuessViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    self.title = @"金价预测";
    [self configSubView];
    [self sendCommentRequest];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page ++ ;
        [self sendCommentRequest];
    }];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self sendCommentRequest];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.upWaveControl beginAnimation];
    [self.lowWaveControl beginAnimation];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    header.backgroundColor = [UIColor whiteColor];
    
    UIView * yeallowView = [[UIView alloc] initWithFrame:CGRectMake(20,0 +10 , 4, 15 )];
    yeallowView.backgroundColor = TM_orangeColor;
    yeallowView.centerY = 22;
    [header addSubview:yeallowView];
    
    NSString * totol = self.guessModel.total.description;
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(yeallowView.right + 15, yeallowView.top, 200, 15)
                                                     text:[NSString stringWithFormat:@"%@%@",totol,@"人正在参与"]
                                                textColor:TM_secendTextColor
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:totol attributes:@{NSForegroundColorAttributeName:TM_orangeColor}];
    titleLable.centerY = 22;
    [header addSubview:titleLable];
    __weak typeof(self) weakSelf =  self;
    STButton * historyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 200, 44)
                                                     title:@"历史正确率76%"
                                                titleColor:TM_secendTextColor
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"问号"]];
    historyButton.right = UIScreenWidth - 15;
    [historyButton setClicAction:^(UIButton *sender) {
        TMGNotePresentViewController * note = [TMGNotePresentViewController new];
        note.titleString = @"历史正确率";
        note.note = @"历史正确率=预测正确的天数/历史预测总天数。\n当平台多数用户的判断和当日实际走势相符时,计为预算正确。";
        [weakSelf presentViewController:note animated:NO completion:nil];
    }];
    [historyButton makeImageRight];
    historyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [header addSubview:historyButton];
    
    UIView * line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 44, UIScreenWidth, 0.5)];
    line1.backgroundColor = TM_lineColor;
    [header addSubview:line1];
    
    self.upWaveControl = [[TMWaveView alloc] initWithFrame:CGRectMake(0, line1.bottom, UIScreenWidth / 2, 100)
                                              waveTopColor:TM_redColor
                                           waveBootomColor:FlatWhiteDark
                                                     title:[NSString stringWithFormat:@"%@的人看涨",self.guessModel.up]
                                                titleColor:TM_redColor
                                                   persent:0.8];
    NSString * up = [self.guessModel.up stringByReplacingOccurrencesOfString:@"%" withString:@""];
    self.upWaveControl.wavePresent = up.floatValue / 100;
    [header addSubview:self.upWaveControl];
    self.lowWaveControl = [[TMWaveView alloc] initWithFrame:CGRectMake(_upWaveControl.right, line1.bottom, UIScreenWidth / 2, 100)
                                               waveTopColor:FlatMint
                                            waveBootomColor:FlatWhiteDark
                                                      title:[NSString stringWithFormat:@"%@的人看跌",self.guessModel.down]
                                                 titleColor:FlatMint
                                                    persent:0.1];
    NSString * down = [self.guessModel.down stringByReplacingOccurrencesOfString:@"%" withString:@""];
    self.lowWaveControl.wavePresent = down.floatValue / 100;
    [header addSubview:self.lowWaveControl];
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, _lowWaveControl.bottom, UIScreenWidth, 0.5)];
    line.backgroundColor = TM_lineColor;
    [header addSubview:line];
    
    STButton * lowButton = [[STButton alloc] initWithFrame:CGRectMake(0, line.bottom, UIScreenWidth / 3, 44)
                                                     title:@"看跌"
                                                titleColor:TM_thirdTextColor
                                                 titleFont:13
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"看跌_01"]];
    lowButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [lowButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLowButton:sender];
    }];
    [lowButton st_showRightLine:30];
    lowButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [header addSubview:lowButton];
        CGRect temRect = lowButton.frame;
    STButton * upButton = [[STButton alloc] initWithFrame:CGRectMake(lowButton.right, line.bottom, UIScreenWidth / 3, 44)
                                                    title:@"看涨"
                                               titleColor:TM_redColor
                                                titleFont:13
                                             cornerRadius:0
                                          backgroundColor:nil
                                          backgroundImage:nil
                                                    image:[UIImage imageNamed:@"看涨_01"]];
    upButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [upButton st_showRightLine:30];
    upButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [upButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedUpButton:sender];
    }];
    [header addSubview:upButton];
    
    STButton * commentButton = [[STButton alloc] initWithFrame:CGRectMake(upButton.right, line.bottom, UIScreenWidth / 3, 44)
                                                         title:@"评论"
                                                    titleColor:TM_secendTextColor
                                                     titleFont:13
                                                  cornerRadius:0
                                               backgroundColor:nil
                                               backgroundImage:nil
                                                         image:[UIImage imageNamed:@"评论"]];
    commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    commentButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [commentButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommentButton:sender];
    }];
    [header addSubview:commentButton];
    
    
    lowButton.frame = upButton.frame;
    upButton.frame = temRect;
    
    
    UIView * grawView = [[UIView alloc] initWithFrame:CGRectMake(0, commentButton.bottom, UIScreenWidth, 10)];
    grawView.backgroundColor = TM_backgroundColor;
    [header addSubview:grawView];
    
    header.height = grawView.bottom;
    self.tableView.tableHeaderView = header;
    
    [self.tableView reloadData];
    
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    TMGCommentModel * model = self.dataSouce[indexPath.row];
    return model.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 44;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)];
    sectionHeader.backgroundColor = [UIColor whiteColor];
    NSInteger people = self.guessModel.total_comment.integerValue;
    if (!people) {
        people = self.dataSouce.count;
    }
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, 200, 44)
                                                     text:[NSString stringWithFormat:@"全部评论(%@)",@(people)]
                                                textColor:TM_secendTextColor
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [sectionHeader addSubview:titleLable];
    return sectionHeader;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    TMGCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[TMGCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    __weak typeof(self) weakSelf =  self;
    TMGCommentModel * model = self.dataSouce[indexPath.row];
    cell.model = model;
    [cell.goodButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedGoodButtonWithIndexPath:indexPath];
    }];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.navigationController pushViewController:[TMGCommentViewController new] animated:YES];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSelctedGoodButtonWithIndexPath:(NSIndexPath*)indexPath{
    [self sendGoodRequestWithIndexPath:indexPath];
}
- (void)onSelectedLowButton:(UIButton*)sender{
    [self sendGoldGuessRequestWithTYpe:@"2"];
}
- (void)onSelectedUpButton:(UIButton*)sender{
    [self sendGoldGuessRequestWithTYpe:@"1"];
}
- (void)onSelectedCommentButton:(UIButton*)sender{
  [self.navigationController pushViewController:[TMGCommentViewController new] animated:YES];
}
#pragma mark --NetWork Method
- (void)sendCommentRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/getCommentDetails"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 NSArray * array = responseObject[@"data"];
                                                 if (self.page == 1) {
                                                     self.dataSouce = [NSMutableArray new];
                                                 }
                                                 for (NSDictionary * dataDic in array) {
                                                     TMGCommentModel * model = [TMGCommentModel mj_objectWithKeyValues:dataDic];
                                                     [self.dataSouce addObject:model];
                                                 }
                                                 [self.tableView reloadData];
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView.mj_footer endRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                             }];
}
- (void)sendGuessRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/guessData"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 TMGGuessModel * model = [TMGGuessModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 self.guessModel = model;
                                                 [self configSubView];
                                                 [SVProgressHUD dismiss];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGoldGuessRequestWithTYpe:(NSString*)type{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (type.length) {
        [dic setObject:type forKey:@"type"];
    }
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/guessUp"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 //[self sendGuessRequest];
                                                 NSString * title = @"看跌成功";
                                                 if ([type isEqualToString:@"1"]) {
                                                     title = @"看涨成功";
                                                 }
                                                 [SVProgressHUD showSuccessWithStatus:title];
                                                 [self sendGuessRequest];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGoodRequestWithIndexPath:(NSIndexPath*)indexPath{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    TMGCommentModel * model = self.dataSouce[indexPath.row];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    [dic setObject:model.commentID forKey:@"id"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/quotes/thumbs"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {

                                                 [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
                                                 model.is_thumb  =@(1);
                                                 NSInteger thumbs = model.thumbs.integerValue;
                                                 model.thumbs = @(thumbs + 1);
                                                 [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
